/**
 * 
 */
package dev.gu.study.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;

/**
 * @author guweichao
 * @created 2019年4月11日
 * @desc iprocess数据源
 */
@Configuration
@EnableTransactionManagement
//配置mybatis的接口类放的地方
@MapperScan(basePackages = "dev.gu.study.bean.datasource1", sqlSessionFactoryRef = "ds1SqlSessionFactory")
public class DataSourceConfig1 {
	// 将这个对象放入Spring容器中
	@Bean(name = "ds1DataSource")
	// 表示这个数据源是默认数据源
	@Primary
	// 读取application.properties中的配置参数映射成为一个对象
	// prefix表示参数的前缀
	@ConfigurationProperties(prefix = "spring.datasource.datasource1")
	public DataSource getDateSource1() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "ds1SqlSessionFactory")
	// 表示这个数据源是默认数据源
	@Primary
	// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
	public MybatisSqlSessionFactoryBean iProcessSqlSessionFactory(
			@Qualifier("ds1DataSource") DataSource datasource) throws Exception {
		MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(getDateSource1());
		MybatisConfiguration configuration = new MybatisConfiguration(); configuration.addInterceptor(new PaginationInterceptor());
		configuration.setMapUnderscoreToCamelCase(false); 
		sqlSessionFactoryBean.setConfiguration(configuration);
//	         sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*Mapper.xml"));
		return sqlSessionFactoryBean;
	}

	@Bean("ds1SqlSessionTemplate")
	// 表示这个数据源是默认数据源
	@Primary
	public SqlSessionTemplate test1sqlsessiontemplate(
			@Qualifier("ds1SqlSessionFactory") SqlSessionFactory sessionfactory) {
		return new SqlSessionTemplate(sessionfactory);
	}

	/**
	 * @description 事务管理
	 * @author guweichao
	 * @created_at 2019年4月29日 上午9:23:32
	 * @param sitDataSource
	 * @return
	 */
	@Bean(name="iTxManager")
	public PlatformTransactionManager iTransactionManager() {
		return new DataSourceTransactionManager(getDateSource1());
	}
}
